// 系统监控页面逻辑：监控项目心跳状态和休息区占用情况
(function () {
    var alertShown = false;
    var isLoading = false;
    
    // 更新项目心跳状态
    function updateHeartbeatStatus() {
        if (isLoading) return;
        isLoading = true;
        
        // 显示加载状态
        showLoadingState('heartbeat');
        
        apiService.getSystemHeartbeat()
            .then(function (data) {
                console.log('心跳状态数据:', data);
                
                // 处理不同的数据格式
                if (data.projects) {
                    // 新格式：{ projects: { rollerCoaster: {...}, vrCinema: {...}, restArea: {...}, foodStreet: {...}, shuttle: {...}, entranceExit: {...} } }
                    updateProjectHeartbeat('rollerCoaster', data.projects.rollerCoaster);
                    updateProjectHeartbeat('vrCinema', data.projects.vrCinema);
                    updateProjectHeartbeat('restArea', data.projects.restArea);
                    updateProjectHeartbeat('foodStreet', data.projects.foodStreet);
                    updateProjectHeartbeat('shuttle', data.projects.shuttle);
                    updateProjectHeartbeat('entranceExit', data.projects.entranceExit);
                } else {
                    // 旧格式：{ rollerCoaster: {...}, vrCinema: {...}, restArea: {...}, foodStreet: {...}, shuttle: {...}, entranceExit: {...} }
                    updateProjectHeartbeat('rollerCoaster', data.rollerCoaster || data.roller_coaster);
                    updateProjectHeartbeat('vrCinema', data.vrCinema || data.vr_cinema);
                    updateProjectHeartbeat('restArea', data.restArea || data.rest_area);
                    updateProjectHeartbeat('foodStreet', data.foodStreet || data.food_street);
                    updateProjectHeartbeat('shuttle', data.shuttle);
                    updateProjectHeartbeat('entranceExit', data.entranceExit || data.entrance_exit);
                }
                
                hideLoadingState('heartbeat');
            })
            .catch(function (err) {
                console.error('获取心跳状态失败:', err);
                hideLoadingState('heartbeat');
                // 显示错误状态
                setProjectStatus('rollerCoaster', 'danger', '连接失败');
                setProjectStatus('vrCinema', 'danger', '连接失败');
                setProjectStatus('restArea', 'danger', '连接失败');
                setProjectStatus('foodStreet', 'danger', '连接失败');
                setProjectStatus('shuttle', 'danger', '连接失败');
                setProjectStatus('entranceExit', 'danger', '连接失败');
            })
            .finally(function() {
                isLoading = false;
            });
    }
    
    function updateProjectHeartbeat(project, data) {
        if (!data) return;
        
        var status = data.status || 'normal';
        var lastHeartbeat = data.lastHeartbeat || data.last_heartbeat || new Date().toISOString();
        var timeAgo = getTimeAgo(lastHeartbeat);
        
        setProjectStatus(project, status, timeAgo);
        
        // 检查危险信号
        if (status === 'danger' && !alertShown) {
            showAlert('项目 ' + getProjectName(project) + ' 出现异常，请立即检查！');
            alertShown = true;
        }
    }
    
    function setProjectStatus(project, status, timeText) {
        var statusEl = document.getElementById(project + 'Status');
        var timeEl = document.getElementById(project + 'Time');
        
        if (statusEl) {
            statusEl.textContent = getStatusText(status);
            statusEl.className = 'status-indicator ' + status;
        }
        
        if (timeEl) {
            timeEl.textContent = timeText;
        }
    }
    
    function getStatusText(status) {
        switch (status) {
            case 'normal': return '正常';
            case 'warning': return '警告';
            case 'danger': return '危险';
            default: return '未知';
        }
    }
    
    function getProjectName(project) {
        switch (project) {
            case 'rollerCoaster': return '激流勇进';
            case 'vrCinema': return 'VR影院';
            case 'restArea': return '休息区';
            case 'foodStreet': return '美食街';
            case 'shuttle': return '摆渡车';
            case 'entranceExit': return '出入口';
            default: return '未知项目';
        }
    }
    
    function getTimeAgo(timestamp) {
        var now = new Date();
        var time = new Date(timestamp);
        var diff = Math.floor((now - time) / 1000);
        
        if (diff < 60) return '刚刚';
        if (diff < 3600) return Math.floor(diff / 60) + '分钟前';
        if (diff < 86400) return Math.floor(diff / 3600) + '小时前';
        return Math.floor(diff / 86400) + '天前';
    }
    
    // 更新休息区座位占用情况
    function updateSeatingOccupancy() {
        if (isLoading) return;
        
        // 显示加载状态
        showLoadingState('seating');
        
        apiService.getSeatingOccupancy()
            .then(function (data) {
                console.log('座位占用数据:', data);
                
                // 处理不同的数据格式
                if (data.areas) {
                    // 新格式：{ areas: { areaA: {...}, areaB: {...} } }
                    updateAreaOccupancy('areaA', data.areas.areaA);
                    updateAreaOccupancy('areaB', data.areas.areaB);
                } else {
                    // 旧格式：{ areaA: {...}, areaB: {...} }
                    updateAreaOccupancy('areaA', data.areaA || data.area_a);
                    updateAreaOccupancy('areaB', data.areaB || data.area_b);
                }
                
                hideLoadingState('seating');
            })
            .catch(function (err) {
                console.error('获取座位占用情况失败:', err);
                hideLoadingState('seating');
                // 显示错误状态
                showSeatingError();
            });
    }
    
    function updateAreaOccupancy(area, data) {
        if (!data) return;
        
        var occupied = data.occupied || data.occupied_count || 0;
        var total = data.total || data.total_count || 100;
        var percentage = Math.round((occupied / total) * 100);
        
        var fillEl = document.getElementById(area + 'Occupancy');
        var textEl = document.getElementById(area + 'Text');
        
        if (fillEl) {
            fillEl.style.width = percentage + '%';
            fillEl.className = 'occupancy-fill';
            
            if (percentage >= 90) {
                fillEl.className += ' full';
            } else if (percentage >= 70) {
                fillEl.className += ' high';
            }
        }
        
        if (textEl) {
            textEl.textContent = '占用: ' + occupied + '/' + total + ' (' + percentage + '%)';
        }
    }
    
    // 显示危险信号弹窗
    function showAlert(message) {
        var modal = document.getElementById('alertModal');
        var messageEl = document.getElementById('alertMessage');
        
        if (modal && messageEl) {
            messageEl.textContent = message;
            modal.style.display = 'flex';
        }
    }
    
    // 显示加载状态
    function showLoadingState(type) {
        if (type === 'heartbeat') {
            var cards = document.querySelectorAll('.heartbeat-card');
            cards.forEach(function(card) {
                card.classList.add('loading');
            });
        } else if (type === 'seating') {
            var cards = document.querySelectorAll('.seating-card');
            cards.forEach(function(card) {
                card.classList.add('loading');
            });
        }
    }
    
    // 隐藏加载状态
    function hideLoadingState(type) {
        if (type === 'heartbeat') {
            var cards = document.querySelectorAll('.heartbeat-card');
            cards.forEach(function(card) {
                card.classList.remove('loading');
            });
        } else if (type === 'seating') {
            var cards = document.querySelectorAll('.seating-card');
            cards.forEach(function(card) {
                card.classList.remove('loading');
            });
        }
    }
    
    // 显示座位错误状态
    function showSeatingError() {
        var areas = ['areaA', 'areaB'];
        areas.forEach(function(area) {
            var textEl = document.getElementById(area + 'Text');
            if (textEl) {
                textEl.textContent = '数据获取失败';
                textEl.style.color = '#dc3545';
            }
        });
    }
    
    // 关闭弹窗
    window.closeAlert = function() {
        var modal = document.getElementById('alertModal');
        if (modal) {
            modal.style.display = 'none';
            alertShown = false;
        }
    };
    
    // 页面加载时开始监控
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function () {
            updateHeartbeatStatus();
            updateSeatingOccupancy();
            // 每10秒更新一次
            setInterval(updateHeartbeatStatus, 10000);
            setInterval(updateSeatingOccupancy, 10000);
        });
    } else {
        updateHeartbeatStatus();
        updateSeatingOccupancy();
        setInterval(updateHeartbeatStatus, 10000);
        setInterval(updateSeatingOccupancy, 10000);
    }
})();
